package cn.yuan.arithmetic.sort;

/**
 * 快速排序实现.
 *
 * @author : yjs
 * @date: 2020-12-17 11:13
 */
public class QuickSort {
    public static void main(String[] args) {
        int[] array = {3, 4, 7, 4, 1, 9, 13, 24, 11, 45, 22, 45};
        System.out.println(print(array));
        QuickSort.sort(array);
        System.out.println(print(array));
    }

    /**
     * 实现
     */
    public static void sort(int[] array) {
        if (array.length > 0) {
            quickSort(array, 0, array.length - 1);
        }
    }
    private static void quickSort(int[] a, int low, int high) {
        if (low < high) { // 如果不加这个判断递归会无法退出导致堆栈溢出异常
            int middle = getMiddle(a, low, high);
            quickSort(a, 0, middle - 1);
            quickSort(a, middle + 1, high);
        }
    }
    private static int getMiddle(int[] a, int low, int high) {
        int temp = a[low];// 基准元素
        while (low < high) {
            // 找到比基准元素小的元素位置
            while (low < high && a[high] >= temp) {
                high--;
            }
            a[low] = a[high];
            while (low < high && a[low] <= temp) {
                low++;
            }
            a[high] = a[low];
        }
        a[low] = temp;
        return low;
    }

    /**
     * 打印
     */
    private static String print(int[] array) {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < array.length; i++) {
            sb.append(array[i]);
            if (i < array.length - 1) {
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}
